<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');
	
require_once(APPPATH."libraries/facebook/FacebookSession.php");
require_once(APPPATH."libraries/facebook/FacebookRedirectLoginHelper.php");
require_once(APPPATH."libraries/facebook/FacebookRequest.php");
require_once(APPPATH."libraries/facebook/FacebookResponse.php");
require_once(APPPATH."libraries/facebook/FacebookSDKException.php");
require_once(APPPATH."libraries/facebook/FacebookRequestException.php");
require_once(APPPATH."libraries/facebook/FacebookAuthorizationException.php");
require_once(APPPATH."libraries/facebook/GraphObject.php");
require_once(APPPATH."libraries/facebook/GraphUser.php");
require_once(APPPATH."libraries/facebook/GraphSessionInfo.php");




require_once(APPPATH."libraries/facebook/Entities/AccessToken.php");
require_once(APPPATH."libraries/facebook/HttpClients/FacebookHttpable.php");
require_once(APPPATH."libraries/facebook/HttpClients/FacebookCurlHttpClient.php");
require_once(APPPATH."libraries/facebook/HttpClients/FacebookCurl.php");




use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;

use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\GraphUser;
use Facebook\GraphSessionInfo;

class facebook {
	var $ci;
    var $helper;
    var $session;
	public function __construct() {
		
        $this->ci =& get_instance();
		if ( session_status() == PHP_SESSION_NONE ) {
			session_start();
		}
		$this->ci->config->load('facebook');
        FacebookSession::setDefaultApplication( $this->ci->config->item('api_id', 'facebook'), $this->ci->config->item('app_secret', 'facebook') );
        $this->helper = new FacebookRedirectLoginHelper( $this->ci->config->item('redirect_url', 'facebook') );
		
        if ( $this->ci->session->userdata('fb_token') ) {
            $this->session = new FacebookSession( $this->ci->session->userdata('fb_token') );
			
            // Validate the access_token to make sure it's still valid
            try {
                if ( ! $this->session->validate() ) {
					$this->session = false;
                }
				} catch ( Exception $e ) {
                // Catch any exceptions
                $this->session = false;
            }
        } else {
            try {
                $this->session = $this->helper->getSessionFromRedirect();
				} catch(FacebookRequestException $ex) {
                // When Facebook returns an error
				} catch(\Exception $ex) {
                // When validation fails or other local issues
            }
        }
		
        if ( $this->session ) {
            $this->ci->session->set_userdata( 'fb_token', $this->session->getToken() );
			
            $this->session = new FacebookSession( $this->session->getToken() );
        }
    }
	
	public function get_login_url() {
        return $this->helper->getLoginUrl( $this->ci->config->item('permissions', 'facebook') );
    }
	
    public function get_logout_url() {
        if ( $this->session ) {
            return $this->helper->getLogoutUrl( $this->session, site_url( 'logout' ) );
        }
        return false;
    }
	public function check_login() {
		return ($this->session)?true:false;
		
	}
    public function get_user() {
        if ( $this->session ) {
            try {
                $request = (new FacebookRequest( $this->session, 'GET', '/me' ))->execute();
                $user = $request->getGraphObject()->asArray();
				
                return $user;
				
				} catch(FacebookRequestException $e) {
                return false;
				
                /*echo "Exception occured, code: " . $e->getCode();
                echo " with message: " . $e->getMessage();*/
            }
        }
    }
	
	function get_user_field($field = ''){
		if ( $this->session ) {
            try {
                $request = (new FacebookRequest( $this->session, 'GET', '/me/'.$field ))->execute();
                $user = $request->getGraphObject()->asArray();
				
                return $user;
				
				} catch(FacebookRequestException $e) {
                return false;
				
                /*echo "Exception occured, code: " . $e->getCode();
                echo " with message: " . $e->getMessage();*/
            }
        }
	}
	
	function get_field($field = ''){
		if ( $this->session ) {
            try {
                $request = (new FacebookRequest( $this->session, 'GET', $field ))->execute();
                $user = $request->getGraphObject()->asArray();
				
                return $user;
				
				} catch(FacebookRequestException $e) {
                return false;
				
                /*echo "Exception occured, code: " . $e->getCode();
                echo " with message: " . $e->getMessage();*/
            }
        }
	}
	
	function get_avatar($width = '' , $height = ''){
		if ( $this->session ) {
            try {
				if($width != '')
					$width = '&width='.$width;
				if($height != '')
					$height = '&height='.$height;
                $avatar = $this->get_user_field('picture?type=normal&redirect=false'.$width.$height);
				if(isset($avatar->url))
					return $avatar->url;
				} catch(FacebookRequestException $e) {
                return false;
				
                /*echo "Exception occured, code: " . $e->getCode();
                echo " with message: " . $e->getMessage();*/
            }
        }
		
	}
	function get_friends(){
		if ( $this->session ) {
            try {
                $friends = $this->get_user_field('friends?limit=5000');
				$arr_friend = array();
				if(isset($friends['data']) && count($friends['data']) >0){
					foreach($friends['data'] as $f){
						$arr_friend[] = $f;
					}
					
				}
				return $arr_friend;
				} catch(FacebookRequestException $e) {
                return false;
            }
        }
		
	}
	function get_id_friends(){
		if ( $this->session ) {
            try {
                $friends = $this->get_friends();
				$arr_friend = array();
				foreach($friends as $friend){
					$arr_friend[] = $friend->id;
					
				}
				return $arr_friend;
				} catch(FacebookRequestException $e) {
                return false;
            }
        }
	}
	
}